//
//  XYOAuthViewController.swift
//  01.XinLangWB
//
//  Created by 肖玉东 on 16/4/15.
//  Copyright © 2016年 苏小样. All rights reserved.
//

import UIKit
import SVProgressHUD
//private let userInfoKey = "com.itheima.userInfoKey"
class XYOAuthViewController: UIViewController {
    //创建根视图
    let webView = UIWebView()
    override func loadView() {
        view = webView
        
        webView.delegate = self
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "关闭", target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem( title: "自动填充", target: self, action: "fullAccount")
        //使用webView加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?"+"client_id="+client_id+"&redirect_uri="+redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        //隐藏HUD
        SVProgressHUD.dismiss()
        
    }
    //关闭页面
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
   //自动填充  在发布的时候一定要删除
    @objc private func  fullAccount(){
        //设置默认的账号密码
 webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '1279686361@qq.com' ,document.getElementById('passwd').value = '123456789qwe'")
    }
    
 

}

//遵守webView的协议
extension XYOAuthViewController: UIWebViewDelegate{
    //开始加载页面
    func webViewDidStartLoad(webView: UIWebView) {
        //开启等待指示器
        SVProgressHUD.show()
    }
    //页面加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //设置标题
        let webTitle = webView.stringByEvaluatingJavaScriptFromString("document.title")
        title = webTitle
        //关闭等待指示器
        SVProgressHUD.dismiss()
    }
    //在授权回调成功页中获取code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //获取路径
        let urlString = request.URL?.absoluteString ?? ""
        let flag = "code="
        //满足包含字符串
        if urlString.containsString(flag) {
            let range = urlString.rangeOfString(flag)!
            let code = urlString.substringFromIndex(range.endIndex)
            print(code)
            //使用授权码获取accesstoken
            //不加载授权成功的回调页面
            //loadAccessToken(code)
            XYUserAccountViewModel.shareAccountModel.loadAccessToken(code, finished: { (isSucceed) -> () in
                if !isSucceed {
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                }
                // TODO:跳转到欢迎界面
//                SVProgressHUD.showSuccessWithStatus("登录成功")
                 //OAuth 是一个被 modal出来的页面  需要手动dismiss 不然会造成页面无法释放
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                   //不推荐这种方式切换根视图控制器
//                    UIApplication.sharedApplication().keyWindow?.rootViewController = XYWelcomeViewController()
                    NSNotificationCenter.defaultCenter().postNotificationName(XYSwitchRootViewController, object: nil)
                })
                
            })
            //不加载授权成功的回调页面
            return false
        }
        return true
    }

}



